
type ForEachPropsType = {
  data: any[] | Record<string | number, any> | number
  render: (item: any, key: string | number) => JSX.Element
  filter?: (item: any, key: string | number) => boolean
}
/**
 * 遍历组件
 */
function ForEach ({ data, render, filter = () => true }: ForEachPropsType) {
  const items: JSX.Element[] = []
  if (Array.isArray(data)) { // 数组
    data.forEach((item, index) => {
      if (filter(item, index)) {
        items.push(render(item, index))
      }
    })
  } else if (typeof data === 'number') { // 数字
    let i = 1
    while (i <= data) {
      if (filter(i, i - 1)) {
        items.push(render(i, i - 1))
      }
      i++
    }
  } else { // 字面量对象
    Object.entries(data).forEach(([key, item]) => {
      if (filter(item, key)) {
        items.push(render(item, key))
      }
    })
  }

  return (<>{items}</>)
}

export default ForEach
